<?php
require_once "CMS_Login.class.php";

/*
 * added by cliff on 2011/5/4 - 2011/5/5
 * modified search_build_sql to support date_range and range needed to update HTMLComponent.php too
 * 
 *
 *      28/2/2012       Fixed landing lost when update new password
 *                              override function self_url
 */

class CMS extends CMS_Login{
	
	
	function _save_search_setting($field_name, $match_type, $value){
		# impl later, 
	}
	
	#h_row is default value
  function process_showsearch_feature($dbh_r, $h_feature, $h_row=array()){
    $h_row_final = array();

    
    $a_match = array(
                 'substring'  => 'like',
                 'imatch'   => 'match', #Case insensitive 
                 'match'      => 'Exact match',
                 
                 ##'date_range' => 'date_range',

                 #'range'      => 'range',   #(e.g \'1-100\')
                 #'multiple'   => 'match one of',
                 'not_empty'  => 'Not empty',
                 );
    
    $a_match_int = array(
                 'smart_int'  => 'Match, range or match one of'
                 # select match, range, multiple by input 
                 );
    
    $a_cond = array('and' => 'and', 'or' => 'or', 'and (' => 'and (',
                'or (' => 'or (', ') and' => ') and', ')'=>')');
                
#    foreach ($h_row as $colname => $default_value){
#      $h_row_final[$colname] = $default_value;      
#    }

    $auto_h_feature = array();
  	foreach ($h_feature as $colname => $col_value){
      $auto_field_cond   = $colname.'__COND';
  		$auto_field_match  = $colname.'__MATCH';
  		$auto_field_option = $colname.'__OPTION';
  		
  		if ($col_value == ''){
        $auto_h_feature[$colname]           = array('text',   $colname,           '', array('id'=>'search_'.$colname));
        $auto_h_feature[$auto_field_cond]   = array('h:list', $auto_field_cond,   $a_cond, array('id'=>'search_'.$auto_field_cond));
        $auto_h_feature[$auto_field_match]  = array('h:list', $auto_field_match,  $a_match, array('id'=>'search_'.$auto_field_match));
        $auto_h_feature[$auto_field_option] = array('hidden', $auto_field_option, '', array('id'=>'search_'.$auto_field_option));
  		} elseif ($col_value == 'search_int'){
        $auto_h_feature[$colname]           = array('text',   $colname,           '', array('id'=>'search_'.$colname));
        $auto_h_feature[$auto_field_cond]   = array('h:list', $auto_field_cond,   $a_cond, array('id'=>'search_'.$auto_field_cond));
        $auto_h_feature[$auto_field_match]  = array('h:list', $auto_field_match,  $a_match_int, array('id'=>'search_'.$auto_field_match));
        $auto_h_feature[$auto_field_option] = array('hidden', $auto_field_option, '', array('id'=>'search_'.$auto_field_option));
      
      } elseif ($col_value == 'date_range' || $col_value == 'range'){
      	$original_default = isset($h_row[$colname]) ? $h_row[$colname] : '';
      	list($default_start, $default_end) = $this->safe_explode('-', $original_default,  2);
      	$range_html = html_text($default_start, $colname.'_start').' - '.html_text($default_end, $colname.'_end');
      	
      	$auto_h_feature[$colname]          = array('asis',   $colname);
      	$h_row[$colname]=$range_html;
      	                                                                            
        $auto_h_feature[$auto_field_cond]   = array('h:list', $auto_field_cond,   $a_cond, array('id'=>'search_'.$auto_field_cond));
        $auto_h_feature[$auto_field_match]  = array('h:list', $auto_field_match,  $a_match, array('id'=>'search_'.$auto_field_match));
        $auto_h_feature[$auto_field_option] = array('hidden', $auto_field_option, '', array('id'=>'search_'.$auto_field_option));        
        
      } else {
        #if (!isset($col_value[2])) $col_value[2] = '';
        #array_push($col_value, array('id'=>'search_'.$colname));
        #$auto_h_feature[$colname]           = array($col_value,   $colname,       '', array('id'=>'search_'.$colname));
        # checkbox
        
        ###################
        #$feature_option = array();
        #if (isset($col_value[3])){ # the fourth, probably an array of option
        #	$feature_option = $col_value[3];
        #}
        
	
	
        #if (isset($feature_option['#OTM#'])){
        #	unset($feature_option['#OTM#']);
        #	$col_value[3] = $feature_option;
        #	$auto_h_feature[$colname]           = $col_value; # remove the '#OTM#', which is not used in layout
        #  $auto_h_feature[$auto_field_cond]   = array('h:list', $auto_field_cond,   $a_cond, array('id'=>'search_'.$auto_field_cond));
        #  $auto_h_feature[$auto_field_option] = array('hidden', $auto_field_option, '', array('id'=>'search_'.$auto_field_option));
        #  $h_row[$auto_field_option] = 'otm';
        #  echo "HI $auto_field_option] = 'otm'";
        #} else {
          $auto_h_feature[$colname]           = $col_value;
          $auto_h_feature[$auto_field_cond]   = array('h:list', $auto_field_cond,   $a_cond, array('id'=>'search_'.$auto_field_cond));
          $auto_h_feature[$auto_field_option] = array('hidden', $auto_field_option, '', array('id'=>'search_'.$auto_field_option));
        #}
      }
    }
    
  	foreach ($auto_h_feature as $colname => $col_value){
  		#if (!empty($col_value)){
        $h_row_final[$colname] = $this->process_feature($dbh_r, $h_row, $colname, $auto_h_feature);
      #}
#       else {
#echo("$colname => $col_value");
       # $h_row_final[$colname.'_cond'] = $this->process_feature($dbh_r, $h_row, $colname.'_cond', $h_feature);
#      }
	  }
	  return $h_row_final;  	
  }
	
	function search_clear($session_prefix){
		$this->rm_s_param($session_prefix.'SEARCH_COND');  
		
//		$h_session = $this->s_param();
//		$session_prefix =  'test_upload'.'_search:';
//		foreach ($h_session as $k => $v){
//			if ( preg_match("/^$session_prefix/", $k)){
//			  $this->rm_s_param($key);
//			}
//		}
	  
	}




	# return ($flag, $sql)
	#         $flag = 0, have search input
	function search_build_sql($h_feature=array()){
	  $a_searchable_fields = $this->q_param('searchable_fields'); # get the order of field list  
	  #if (! is_array($a_searchable_fields) ){
	  #	return $a_searchable_fields; # invalid search.
	  #}
	  
	  $a_temp = array();  
	
	  foreach ($a_searchable_fields as $field_name ){
	    $match        = $this->get_q($field_name.'__MATCH');
	    $cond         = $this->get_q($field_name.'__COND');
	    $field_option = $this->get_q($field_name.'__OPTION'); # with special UI
	    
	    ###### start for global search ##########
	    
	    if ($field_name == 'global_search'){
	    	$search_field = $h_feature{'global_search'};
	    	$value = $this->get_q('global_search');
	      if ($value == '') continue;
	      		
	    	$a_global_search_field = explode(',', $search_field);
	    	$n_global_search_fields = count($a_global_search_field);
	    	
	    	#echo "n_global_search_fields $n_global_search_fields<BR>\n";
	    	
	    	if ($a_global_search_field == 0) continue;
	    	if ($a_global_search_field == 1){
	    	  array_push($a_temp, $this->search_build_field($a_global_search_field[0], $value, 'substring'), 'and');
	      }
	    	
	    	
	    	#foreach ($a_global_search_field as $global_search_field){
	    	$a_global_search_temp = array();
	    	$last_global_search_field = $n_global_search_fields;
	    	for ($i=0; $i < $n_global_search_fields; $i++){ 	
	    	  $cond = 'or';
	    	  if ( $i == $last_global_search_field){
	    	  	$cond = ')and';
	    	  }
	    	  $global_search_field = $a_global_search_field[$i];
	    	  
	    	  #echo "$global_search_field --<BR>";
	    	  array_push($a_global_search_temp, $this->search_build_field($global_search_field, $value, 'substring'), $cond);
	      }
	      
	      array_pop($a_global_search_temp);
	      array_push($a_temp, '('.implode(' ', $a_global_search_temp).')', 'and');
	    }
	    
	    ###### end for global search ##########
	    
	    if ($match == 'smart_int'){
	    	# set the $match type smartly by the input
	    	$value = $this->get_q($field_name);
	    	
	    	$pos = strpos($value, ',');
	    	if($pos === false) { // string needle NOT found in haystack
        	$pos = strpos($value, '-');
	    	  if($pos !== false) { // string needle NOT found in haystack
	    		  $match = 'range';
          } else {
          	$match = 'match';
          }
        } else {
        	// match ','
	    		$match = 'multiple';
        }
        
        
	    }
	    
	    
	    $value = '';
	    if ( empty_string($field_option) ){
        if ($match == 'not_empty'){
	      
	      } elseif ($match == 'date_range' || $match == 'range'){
	      	
	      	if ($this->get_q($field_name) != ''){
	      	  $value = $this->get_q($field_name);
	      	  $this->_save_search_setting($field_name, 'range', '');	    	    
	      	} else {
	      	
	    	    $start_date = $this->get_q($field_name.'_start');
	    	    $end_date   = $this->get_q($field_name.'_end');
	    	  
	    	    $start_date = preg_replace('/-/', '/', $start_date);
	    	    $end_date = preg_replace('/-/', '/', $end_date);
	    	    $value = $start_date.'-'.$end_date;
	     	    $this->_save_search_setting($field_name, 'range', '');
	    	    if ($this->get_q($field_name.'_start') == '' &&
	    	      $this->get_q($field_name.'_end')   == ''    ) 
	    	      continue;
	    	  }
	    	} else { # checkbox
	    		$mixed_type = $this->get_q($field_name); # for supporting checkbox
		    	if (is_array($mixed_type)){
		    		$value = implode(',', $mixed_type);
		    	} else {
		    		$value = $mixed_type;
		    	}
		    	#echo "build_search_sql - $field_name $value<BR>\n";
		      $this->_save_search_setting($field_name, '', $value); # save the setting in any case
		      #if (count($a_values) == 0) continue;
		      if ( empty_string($value) ) continue; 
		    } 
		    
	    } else {
	    	switch ($field_option){
	    		case 'otm': 
	    		  $otm_feature = $h_feature[$field_name];
	    		  $otm_search_condition = $this->search_build_field_for_otm($field_name, $value, $otm_feature);
	    		  if ($otm_search_condition != ''){
	    		    array_push($a_temp, $otm_search_condition, $cond);
	    		  }
	    		  break;
	    	}
        continue; #continue foreach ($a_searchable_fields
	    }
	    
	    # elseif ($field_option == 'date_range') {
	    #	
	    #	$value = $this->get_q($field_name.'_start').'-'.$this->get_q($field_name.'_end');
	    #	$this->_save_search_setting($field_name, 'range', '');
	    #	if ($this->get_q($field_name.'_start') == '' &&
	    #	    $this->get_q($field_name.'_end')   == ''    ) 
	    #	  continue;
	    #} else {
	    #	continue; # unsported field_option
	    #}    
	    array_push($a_temp, $this->search_build_field($field_name, $value, $match), $cond);
	    $this->log_error('cms', 'search_build_sql - '.implode(',', $a_temp));
	
	  }
	  
	  if (count($a_temp) == 0){
	    return array(1, '');
	  }
	 
	 #$this->s_param('SEARCH_COND', $a_temp);
	  
	 # array_pop($a_temp);
	 # $cond = implode(' ', $a_temp);
	 # echo 'xxxx :'.$cond;
	 # $cond = '('.$cond.')';
	  
	 # $full_condition = " $cond";
	
	  
	 # return array(0, 'select * from '.$this->param('table')." where $full_condition ");
	 return array(0, $a_temp);
	}
	
	# OTM Table 
	function search_build_field_for_otm($field_name, $value, $h_feature){
		#id in (select oid from  test_otm_otm_category where category in (2,3))
		#select oid from  test_otm_otm_category where category in (2,3)
		$mixed_type = $this->get_q($field_name); # for supporting checkbox
  	if (is_array($mixed_type)){
  		if (count($mixed_type) == 0){
  			return '';
  		}
  		$value = implode("','", $mixed_type);
  	} else {
  		if ($mixed_type == ''){
  			return '';
  		} 
  		$value = $mixed_type;
  	}
		
		$otm_table = $h_feature['otm_table'];
		$otm_key_field = $h_feature['otm_key_field'];
		$otm_src_key_field = $h_feature['otm_src_key_field'];
		$otm_value_field = $h_feature['otm_value_field'];
		
		
		
		#$value =
	    $this->log_error('cms', 'search_build_field_for_otm - value:'.$value);
		# need to use fieldname to get: 
		#return "id in (select oid from  test_otm_otm_category where category in ('$value'))";
		return "$otm_src_key_field in (select $otm_key_field from $otm_table where $otm_value_field in ('$value'))";
	}
	
	
	# build partial query for a field
	function search_build_field($name, $value, $match){
		$this->log_error('cms', "build_search_field - $name, $value, $match\n");
	  switch ($match){	 # case insensitive
	  	case 'imatch':
	      $value = db_escape($value);
	      return "($name='$value') ";
	    case 'match':    # case sensitive
	      $value = db_escape($value);
	      return "(binary $name='$value') ";    
	    case 'substring':
	      $value = db_escape($value);
	      return "($name like '%$value%') ";
	    case 'range':       # for int, float, year, and even char
	  	  list ($start_value, $end_value) = $this->safe_explode('-', $value, 2);
	  	  if (!empty_string($start_value) && !empty_string($end_value))
	        return "($name >= '$start_value' and $name <='$end_value') ";
	      if (!empty_string($start_value))
	        return "($name >= '$start_value') ";
	      if (!empty_string($end_value))  
	        return "($name <= '$end_value')   " ;
	      return '';
	    case 'date_range':
	  	  list ($start_date, $end_date) = $this->safe_explode('-', $value, 2);
	  	  if (!empty_string($start_date) && !empty_string($end_date))
	        return "(date($name) >= '$start_date' and date($name) <='$end_date') ";
	      if (!empty_string($start_date))
	        return "(date($name) >= '$start_date') ";
	      if (!empty_string($end_date))  
	        return "(date($name) <= '$end_date')   ";
	      return '';
	    case 'multiple':
	    
	      $a_value = explode(',', $value);
	      $a_temp = array();
	      foreach ($a_value as $value){	      	
	        array_push($a_temp, db_escape($value));
	      }
	    
	      $value = implode("','", $a_temp);
	      
	      return "($name in ('$value'))";
	    case 'not_empty':
	       return "($name <> '')   ";
	       break;	      
	  } // end switch
	}
	
	function safe_explode($delim, $value, $n_item=2){
    $pos = strpos($value, $delim); # comma in key?
	  $a_result = array();
	  if ($pos === false){ # no delim found
	  	array_push($a_result, $value);
	  } else {
	  	$a_result = explode($delim, $value);	
	  }	
	  
	  $curr_n_item = count($a_result);
	  if ($curr_n_item == $n_item){
	  	return $a_result;
	  }
	  if ($curr_n_item > $n_item){
	  	echo "too much";
	  	return array_slice($a_result, 0, $n_item);
	  }
	  for ($i=$curr_n_item;$i<$n_item; $i++){
	  	$a_result[$i] = null;
	  }
	  
	  return $a_result;
	}	
/***************************** start mupload supporting function ******************************/


# common function for mupload
# Description
#   get file list 
#
# Parameter:
#   $field_name: no use in current version.
#                as we just support upload 1 files
function get_mupload_files($field_name){
	
	$a_files=array();

  #$upload        = $this->q_param('mupload_file');               # method 1: upload from files
  $server_folder = $this->q_param('mupload_server_folder');      # method 2: upload to server by ftp
  $ftp_uploaded  = $this->q_param('mupload_ftp_done');
  $upload_http   = $this->get_q('mupload_http', '', 'string'); # method 3: by http, only mupload has this field.
  
  if (is_uploaded_file($_FILES['mupload_file']['tmp_name'])){ # method 1;
      
    #$this->log_error('mupload', "Temp zip file path: $temp_zip_file\n");
    $temp_folder = $this->param('TEMP_UPLOAD').date('His'); # HourMinuteSecond, still have chance of duplication
    if (!file_exists($temp_folder)){
        mkdir($temp_folder, 0775, true);  # recursive create directory
    }    
    $this->param('MUPLOAD_EXTRACTED_FOLDER', $temp_folder);
    list($extract_success, $a_files) = $this->zip_flatten($_FILES['mupload_file']['tmp_name'], $temp_folder);
    if ($extract_success){    	
      sort($a_files); 
    }
    
  } elseif ($ftp_uploaded==1 && !empty_string($server_folder) && is_dir($server_folder)){
      #array_push($a_files, $this->get_files_in_folder($server_folder, false));
      $a_files = $this->get_files_in_folder($server_folder, false);
  } elseif (!empty_string($upload_http)) { # uplaoded by URL
    # echo("get_mupload_files(): $upload_http\n");
    #"line break" is ill-defined. Windows uses CR+LF (\r\n), Linux LF (\n), OSX CR (\r) only.
    #There is a little-known special character \R in preg_* regular exceptions that matches all three:
    #preg_match('/^\R$/', "\r\n"); // 1


    $a_lines = preg_split('/$\R?/m', $upload_http);
		foreach ($a_lines as $line){
      if (!empty_string($line)) 	  
          array_push($a_files, $line);
    }
      
  } else {
    $a_files = array(); # nothing
  }
 
  return $a_files;
}


// This function will flatten a zip file using the ZipArchive class. 
// It will extract all the files in the zip and store them in a single destination directory.  That is, no sub-directories will be created.
// If anyone knows a better way to determine if an entry is a directory, please chime in.  I feel dirty checking for a trailing slash.
// dest shouldn't have a trailing slash
// remove well-known temp file ($temp =~ /Thumbs\.db$/);
function zip_flatten ( $zipfile, $dest='.' ){
  $zip = new ZipArchive;
  if ( $zip->open( $zipfile ) ){
    $a_files = array();
    for ( $i=0; $i < $zip->numFiles; $i++ ){
      $entry = $zip->getNameIndex($i);
      if ( substr( $entry, -1 ) == '/' ) continue; // skip directories
     
      $fp = $zip->getStream( $entry );
      $output = $dest.'/'.basename($entry);
      $ofp = fopen($output , 'w' );
     
      if ( ! $fp )
          throw new Exception('Unable to extract the file.');
     
      while ( ! feof( $fp ) )
          fwrite( $ofp, fread($fp, 8192) );
     
      fclose($fp);
      fclose($ofp);
      array_push($a_files, $output); 
    }

    return array($zip->close(), $a_files);
  } 
  
  return array(false, array());
} 

function rrmdir($dir) {
 if (is_dir($dir)) {
   $folders_and_files = scandir($dir);
   foreach ($folders_and_files as $object) {
     if ($object != "." && $object != "..") {
       if (filetype($dir."/".$object) == "dir") {
       	 $this->rrmdir($dir."/".$object); 
       } else {
       	 unlink($dir."/".$object);
       }	
     }
   }
   reset($folders_and_files);
   rmdir($dir);   
 }
} 

# upload by zip/tar/tgz file need to do some cleanup...
#
function mupload_cleanup(){
	
	$folder  = $this->param('MUPLOAD_EXTRACTED_FOLDER');
	if (empty_string($folder)) return;

  $temp_upload_base = $this->param('TEMP_UPLOAD')	;
	if ($temp_upload_base!= $folder &&
	    !empty_string($temp_upload_base) &&
	     preg_match('/'.preg_quote($temp_upload_base,'/').'/', $folder)){
	  $this->rrmdir($folder);
	}
	$folder  = $this->param('MUPLOAD_EXTRACTED_FOLDER', '');	
}

/***************************** end mupload supporting function ******************************/
	
	
/** Function related to import CSV **/

function import_textarea_csv($dbh_w, $table, $text_from_textarea){
	
	$a_lines = $this->text_to_array($text_from_textarea);
  $header  = array_shift($a_lines); # first line is header
  
  $a_header = explode("\t", trim($header));
  $n_header_item = count($a_header);
  if ($n_header_item == 0){
  	return array(101, 'Incorrect header line in import. (first line)');
  }
  
  $invalid_row=0;
  foreach ($a_lines as $line){
  	$line = trim($line);
  	if (empty_string($line)) continue;
  	$a_data = explode("\t", $line);
  	$n_data_item = count($a_data);  	
  	if ($n_data_item > 0 && $n_header_item >= $n_data_item){
  		$h_data = array();
  		for ($i=0; $i < $n_header_item;$i++){
  			$h_data[$a_header[$i]] = isset($a_data[$i]) ? $a_data[$i] : '';
  		} 
  		$this->add_to_table($dbh_w, $table, $h_data);
  	} else {
  		$invalid_row++;
  		
  	}
  }
  
  if ($invalid_row == 0){
  	return array(0,'');
  }
  return array(102, 'Import data contains '.$invalid_row.' invalid row(s).');
}  

# http://us2.php.net/manual/en/function.fputcsv.php
# http://pear.php.net/manual/en/package.fileformats.spreadsheet-excel-writer.intro.php
function export_to_csv($dbh_r, $table, $sqlstr, $h_feature, $temp_folder){
  list($list_data, $a_pagelist, $a_processed_id) = $this->process_select_result($dbh_r, $sqlstr, $h_feature);
  
  $temp_file = tempnam($temp_folder, 'exp');
  $fp = fopen($temp_file, 'w');
  fwrite($fp, "\xEF\xBB\xBF"); //utf8 bom
  $had_header = 0;
  foreach ($list_data as $h_row){
  	//echo implode(', ', $h_row);
  	if ($had_header==0){
  		fputcsv($fp, array_keys($h_row), ',', '"');
  		$had_header=1;
  	}
  	fputcsv($fp, array_values($h_row), ',', '"');
  }
  fclose($fp);
  
  if (!file_exists($temp_folder)){    
	  mkdir($temp_folder, 0775, true);  # recursive create directory
  }
  $new_temp_file = $temp_file.'.csv';
  rename($temp_file, $new_temp_file);
	return array(0, $new_temp_file);
} 


function export_to_xml($dbh_r, $tablename, $sqlstr, $h_feature, $temp_folder){
  list($list_data, $a_pagelist, $a_processed_id) = $this->process_select_result($dbh_r, $sqlstr, $h_feature);
  
  $xmlstr = "<?xml version='1.0' encoding='UTF-8' ?>\n".
              "<tables></tables>";

  // create the SimpleXMLElement object with an empty <tables> element
  // so that we may have mulitple table in a single XML
  $xml = new SimpleXMLElement($xmlstr);
  $table = $xml->addChild('table');
  $table->addAttribute('name', $tablename);
  foreach ($list_data as $h_row){
  	//echo implode(', ', $h_row);
  	
  	$row = $table->addChild("row");
  
  	foreach ($h_row as $key => $value){
  		$row->addChild($key, $value);
  	} 
  }
  
  $temp_file = tempnam($temp_folder, 'exp');
  $fp = fopen($temp_file, 'w');
  fwrite($fp, $xml->asXML());
  fclose($fp);
  
  if (!file_exists($temp_folder)){    
	  mkdir($temp_folder, 0775, true);  # recursive create directory
  }
  $new_temp_file = $temp_file.'.xml';
  rename($temp_file, $new_temp_file);
	return array(0, $new_temp_file);
} 


function export_to_xml2($dbh_r, $table, $sqlstr, $h_feature, $temp_folder){
  list($list_data, $a_pagelist, $a_processed_id) = $this->process_select_result($dbh_r, $sqlstr, $h_feature);
  
  $temp_file = tempnam($temp_folder, 'exp');
  $fp = fopen($temp_file, 'w');
  fwrite($fp, '<?xml version="1.0" encoding="UTF-8" ?>');
  fwrite($fp, '<table>'); # no xml 'header'
  foreach ($list_data as $h_row){
  	//echo implode(', ', $h_row);
  	$temp = array();
  	foreach ($h_row as $key => $value){
  		array_push($temp, "<$key>$value</$key>"); # cdata!!
  	} 
  	$line = "<row>\n".implode("\n", $temp)."</row>\n\n";
  	fwrite($fp, $line);
  }
  fwrite($fp, '</table>');
  fclose($fp);
  
  if (!file_exists($temp_folder)){    
	  mkdir($temp_folder, 0775, true);  # recursive create directory
  }
  $new_temp_file = $temp_file.'.xml';
  rename($temp_file, $new_temp_file);
	return array(0, $new_temp_file);
} 

/** End Function related to import CSV **/

  function cms_redirect_default_action($h_param = array(), $url_mode='path_info'){
    $this->save_message_to_session();    
    return $this->redirect($this->self_url($h_param, $url_mode));
  }

/* Inject JS function and inject in post-run */
// get JS: no argument
// Save JS: 1 or 2 argument
//    inject_js('js_code'); - inject to the end
function inject_js(){
	$numargs = func_num_args();
  	if (2 <= $numargs) {
      self::carp("Too many arguments sent to inject_js()");
      return false;  		
    }	elseif (1 == $numargs) {
  		$js = func_get_arg(0);
  		$a_js = $this->param('#INJECT_JS#');
  		if (empty($a_js) || !is_array($a_js)){
  			$this->param('#INJECT_JS#', array($js));
  	  } else {
  	  	array_push($a_js, $js);
  	  	$this->param('#INJECT_JS#', $a_js);
  	  }
  	  return;
    }
    # no argument
    $a_js = $this->param('#INJECT_JS#');
  	if (is_array($a_js)){  		
  		return $a_js;
  	}	
  	
  	return array();
}


/**error message dialog*/
  function save_message_to_session(){
  	$a_msg = $this->message();
  	if (is_array($a_msg)){
  	  $this->s_param('#MESSAGE#', $a_msg);
    }
  }
  
  function get_message_from_session(){
  	
  	$temp = $this->s_param('#MESSAGE#');
	  $this->s_param('#MESSAGE#', array());
	  if (is_array($temp)){
	    return $temp;
	  }
  
    return array();
  }

  #for supporting path based cms navigation
  # 1: default: sitewise
  # 2: path base
  # 3: name base
  function get_navigation($type=2){
  	if ($type == 2){
  		$path = $this->get_navigation_path();
  		if ($path != '') return $path;
  		return $this->get_navigation_default();
  	}
  	
  	if ($type == 3 && method_exists($this, 'get_navigation_by_login')){
  		# get_navigation_by_login implemented in CMS_Login.class.php
  		$path = $this->get_navigation_by_login();
  		if ($path != '') return $path;
  		return $this->get_navigation_default();
  	}
  	
  	if ($type == 4 ){ # name then path
  		
  		if (method_exists($this, 'get_navigation_by_login')){
  		  # get_navigation_by_login implemented in CMS_Login.class.php
  		  $path = $this->get_navigation_by_login();
  		  if ($path != '') return $path;
  	  }
  		
  		$path = $this->get_navigation_path();
  		if ($path != '') return $path;
  		return $this->get_navigation_default();
  	}
  	
  	return $this->get_navigation_default();
  }
  
  function get_navigation_path(){
  	$path = $this->get_navigation_by_path();
  	if ($path != '') return $path;
  	return $this->get_navigation_default();
  }
  
  function get_navigation_by_path(){
  	$www_root  = $this->param('WWW');
    $full_path = $this->param('this_cgi');
    
    # path base, search up from directory until file found
  	$default_filename = '/navigation.html';
    $a_path = explode('/', $full_path);
    
    while ( array_pop($a_path)){
      $path = implode('/', $a_path);
      #echo $www_root.$path.'<BR>';
      if (file_exists($www_root.$path.$default_filename)){
      	return $www_root.$path.$default_filename;
      }
    }
    
  	return '';
  }
  
  function get_navigation_default(){
  	return "file:cms/navigation.html";
	//return "file:/home/edigest/cache/tmpl/Smarty/templates/cms/navigation.html";
  }
/* copy from CGIApplication.class.php*/
/*
  function load_action_tmpl($action=null){
        if ($action == null) $action = $this->get_current_runmode();
        $h_tmpl    = $this->param('tmpl');
        $base_path = $h_tmpl['base_path'];
        $tmpl = array_key_exists($action, $h_tmpl) ? $h_tmpl[$action] : $base_path.$action.'.html'; // use base path + action as relative path
        //return $this->load_tmpl($this->param('TMPL'), $tmpl);
		return $this->load_tmpl($tmpl);
  }
*/
  function self_url($h_param = array(), $url_mode=''){
  	$a_path_info = array();
  	if (isset($h_param['action'])){
  	  array_push($a_path_info, $h_param['action']);
  	} else {
  		array_push($a_path_info, $this->start_mode());
  	}
  	
  	if (isset($h_param['oid']))    array_push($a_path_info, $h_param['oid']);
  	if (isset($h_param['topid']))  array_push($a_path_info, $h_param['topid']);
	
	if($url_mode == 'querystr'){
		$temp = array();
		foreach ($h_param as $key => $value){
			array_push($temp, $key.'='.$value);
		}
		return $this->param('SELF_URL').'?'.implode('&', $temp);
	}
	
  	return $this->param('SELF_URL').'/'.implode('/', $a_path_info);
  }
}
?>